package diona.model

import net.liftweb.squerylrecord.KeyedRecord
import org.squeryl.annotations._
import net.liftweb.record.field.{LongField, StringField}
import net.liftweb.record.{MetaRecord, Record}
import net.liftweb.squerylrecord.RecordTypeMode._
/**
 * User: anton
 * Date: 21.04.11 22:56
 */
class DropboxAuth extends Record[DropboxAuth] with KeyedRecord[Long] {
  override def meta = DropboxAuth

  @Column(name = "id")
  override val idField = new LongField(this)

  val authToken = new StringField(this, "")
  val secret = new StringField(this, "")
  val dropboxUid = new StringField(this, "")
  val userId = new LongField(this)
}

object DropboxAuth extends DropboxAuth with MetaRecord[DropboxAuth]  {
  def save(authToken: String, secret: String, dropboxUid: String, user: User): DropboxAuth =
  {
    val authInfo = DropboxAuth.createRecord.authToken(authToken)
      .secret(secret)
      .dropboxUid(dropboxUid).userId(user.id.value)
    inTransaction { PublisherSchema.dropboxAuths.insert(authInfo) }
    authInfo
  }

  def update(authToken: String, secret: String, uid: String, user: User): DropboxAuth =
  {
    inTransaction {
      val authInfo: DropboxAuth = byUser(user).get
      authInfo.authToken(authToken)
      authInfo.dropboxUid(uid)
      authInfo.secret(secret)
      PublisherSchema.dropboxAuths.update(authInfo)
      authInfo
    }
  }

  def byUser(user: User): Option[DropboxAuth] =
  {
    inTransaction {
      PublisherSchema.dropboxAuths.where(a => a.userId === user.id).headOption
    }
  }
}